package grape.workflow.rest.flowable.ui.admin;

import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseConnection;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.resource.ClassLoaderResourceAccessor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.ui.common.service.exception.InternalServerErrorException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Created by yangwei
 * Created at 2020/6/4 13:28
 */
@Slf4j
@ConditionalOnProperty(prefix = "flowable",name = "database-schema-update",havingValue = "true")
@Configuration(proxyBeanMethods = false)
public class AdminDatabaseConfiguration {

    protected static final String LIQUIBASE_CHANGELOG_PREFIX = "ACT_ADM_";

    /**
     * 本来感觉这个没什么用，但添加这个配置会生成act_de_开头的表
     * @param dataSource
     * @return
     */
    @Bean
    public Liquibase adminLiquibase(DataSource dataSource) {
        log.debug("Configuring adminLiquibase");

        Liquibase liquibase = null;
        try {

            DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
            database.setDatabaseChangeLogTableName(LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName());
            database.setDatabaseChangeLogLockTableName(LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName());

            liquibase = new Liquibase("META-INF/liquibase/flowable-admin-app-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
            liquibase.update("flowable");
            return liquibase;

        } catch (Exception e) {
            throw new InternalServerErrorException("Error creating adminLiquibase database", e);
        } finally {
            closeDatabase(liquibase);
        }
    }

    @Bean(name = "minimalDataGenerator")
    public MinimalDataGenerator minimalDataGenerator() {
        return new MinimalDataGenerator();
    }

    private void closeDatabase(Liquibase liquibase) {
        if (liquibase != null) {
            Database database = liquibase.getDatabase();
            if (database != null) {
                try {
                    database.close();
                } catch (DatabaseException e) {
                    log.warn("Error closing adminLiquibase", e);
                }
            }
        }
    }
}
